﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;

namespace Xm.CustomDesigner.UI
{
    public class XmCanvas : Canvas
    {
        internal UIElement? CurrentElement { get; set; }

        //子元素位置
        private System.Windows.Point? _elementPos;


        /// <summary>
        /// 鼠标左键按下
        /// </summary>
        protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            if (e.Source is UIElement element)
            {
                this.CurrentElement = element;

                _elementPos = e.GetPosition(element);//返回鼠标指针相对于指定元素的位置。

                return;
            }
            else
            {
                this.CurrentElement = null;
                _elementPos = null;
            }
        }


        /// <summary>
        /// 拖动
        /// </summary>
        protected override void OnPreviewMouseMove(MouseEventArgs e)
        {
            var pos = e.GetPosition(this);//this是当前的这个canvas

            if (this.CurrentElement != null && _elementPos != null && e.LeftButton == MouseButtonState.Pressed)
            {
                //获取鼠标相对于画布的位置
                var x = pos.X - _elementPos.Value.X;
                var y = pos.Y - _elementPos.Value.Y;

                //将指定元素重设位置，pos.X 和 pos.Y 分别是鼠标相对于 Canvas 左边缘和上边缘的坐标值
                Canvas.SetLeft(this.CurrentElement, x);
                Canvas.SetTop(this.CurrentElement, y);
            }
        }
    }
}
